const Service = require('egg').Service;

class CommentService extends Service {
    // 创建评论
    async create(commentData) {
        const { ctx } = this;

        // 验证帖子是否存在
        const post = await ctx.model.Post.findByPk(commentData.post_id);
        if (!post) {
            throw new Error('帖子不存在');
        }

        // 验证用户是否存在
        const user = await ctx.model.User.findByPk(commentData.user_id);
        if (!user) {
            throw new Error('用户不存在');
        }

        // 如果是对评论的回复，验证父评论是否存在
        if (commentData.parent_id) {
            const parentComment = await ctx.model.Comment.findByPk(commentData.parent_id);
            if (!parentComment) {
                throw new Error('父评论不存在');
            }
            // 确保父评论属于同一个帖子
            if (parentComment.post_id !== commentData.post_id) {
                throw new Error('父评论不属于该帖子');
            }
        }

        // 创建评论
        const comment = await ctx.model.Comment.create({
            ...commentData,
            created_at: new Date(),
            updated_at: new Date(),
        });

        // 更新帖子的评论数量
        await ctx.service.post.updateCommentCount(commentData.post_id, 1);

        return await this.getCommentWithUser(comment.comment_id);
    }

    // 获取评论详情（包含用户信息）
    async getCommentWithUser(commentId) {
        const { ctx } = this;

        const comment = await ctx.model.Comment.findByPk(commentId, {
            include: [
                {
                    model: ctx.model.User,
                    as: 'commenter',
                    attributes: ['user_id', 'nickname', 'avatar']
                },
                {
                    model: ctx.model.Comment,
                    as: 'replies',
                    include: [{
                        model: ctx.model.User,
                        as: 'commenter',
                        attributes: ['user_id', 'nickname', 'avatar']
                    }]
                },
                {
                    model: ctx.model.Comment,
                    as: 'parentComment',
                    include: [{
                        model: ctx.model.User,
                        as: 'commenter',
                        attributes: ['user_id', 'nickname', 'avatar']
                    }]
                }
            ]
        });

        if (!comment) {
            throw new Error('评论不存在');
        }

        return comment;
    }

    // 获取帖子的评论列表（分页，支持层级结构）
    async getPostComments(postId, query) {
        const { ctx } = this;
        const { page = 1, pageSize = 20 } = query;

        // 验证帖子是否存在
        const post = await ctx.model.Post.findByPk(postId);
        if (!post) {
            throw new Error('帖子不存在');
        }

        const options = {
            where: {
                post_id: postId,
                parent_id: null // 只获取顶级评论
            },
            limit: parseInt(pageSize),
            offset: (parseInt(page) - 1) * parseInt(pageSize),
            include: [
                {
                    model: ctx.model.User,
                    as: 'commenter',
                    attributes: ['user_id', 'nickname', 'avatar']
                },
                {
                    model: ctx.model.Comment,
                    as: 'replies',
                    include: [
                        {
                            model: ctx.model.User,
                            as: 'commenter',
                            attributes: ['user_id', 'nickname', 'avatar']
                        },
                        {
                            model: ctx.model.Comment,
                            as: 'replies',
                            include: [{
                                model: ctx.model.User,
                                as: 'commenter',
                                attributes: ['user_id', 'nickname', 'avatar']
                            }]
                        }
                    ]
                }
            ],
            order: [['created_at', 'DESC']]
        };

        const { count, rows } = await ctx.model.Comment.findAndCountAll(options);

        return {
            list: rows,
            pagination: {
                page: parseInt(page),
                pageSize: parseInt(pageSize),
                total: count,
                totalPages: Math.ceil(count / pageSize)
            }
        };
    }

    // 获取评论的所有回复
    async getCommentReplies(commentId, query) {
        const { ctx } = this;
        const { page = 1, pageSize = 20 } = query;

        // 验证评论是否存在
        const comment = await ctx.model.Comment.findByPk(commentId);
        if (!comment) {
            throw new Error('评论不存在');
        }

        const options = {
            where: { parent_id: commentId },
            limit: parseInt(pageSize),
            offset: (parseInt(page) - 1) * parseInt(pageSize),
            include: [{
                model: ctx.model.User,
                as: 'commenter',
                attributes: ['user_id', 'nickname', 'avatar']
            }],
            order: [['created_at', 'ASC']] // 回复按时间正序排列
        };

        const { count, rows } = await ctx.model.Comment.findAndCountAll(options);

        return {
            list: rows,
            pagination: {
                page: parseInt(page),
                pageSize: parseInt(pageSize),
                total: count,
                totalPages: Math.ceil(count / pageSize)
            }
        };
    }

    // 更新评论
    async updateComment(commentId, updateData) {
        const { ctx } = this;

        // 检查评论是否存在
        const comment = await ctx.model.Comment.findByPk(commentId);
        if (!comment) {
            throw new Error('评论不存在');
        }

        // 更新评论信息
        await comment.update({
            content: updateData.content,
            updated_at: new Date()
        });

        return await this.getCommentWithUser(commentId);
    }

    // 删除评论
    async deleteComment(commentId) {
        const { ctx } = this;

        const comment = await ctx.model.Comment.findByPk(commentId);
        if (!comment) {
            throw new Error('评论不存在');
        }

        const postId = comment.post_id;

        // 先删除所有回复
        await ctx.model.Comment.destroy({
            where: { parent_id: commentId }
        });

        // 再删除评论本身
        await comment.destroy();

        // 更新帖子的评论数量（需要重新计算）
        const commentCount = await ctx.model.Comment.count({
            where: { post_id: postId }
        });

        await ctx.model.Post.update(
            { comment_count: commentCount },
            { where: { post_id: postId } }
        );

        return true;
    }

    // 获取用户的评论列表
    async getUserComments(userId, query) {
        const { ctx } = this;
        const { page = 1, pageSize = 20 } = query;

        // 验证用户是否存在
        const user = await ctx.model.User.findByPk(userId);
        if (!user) {
            throw new Error('用户不存在');
        }

        const options = {
            where: { user_id: userId },
            limit: parseInt(pageSize),
            offset: (parseInt(page) - 1) * parseInt(pageSize),
            include: [
                {
                    model: ctx.model.User,
                    as: 'commenter',
                    attributes: ['user_id', 'nickname', 'avatar']
                },
                {
                    model: ctx.model.Post,
                    as: 'post',
                    attributes: ['post_id', 'content'],
                    include: [{
                        model: ctx.model.User,
                        as: 'author',
                        attributes: ['user_id', 'nickname', 'avatar']
                    }]
                }
            ],
            order: [['created_at', 'DESC']]
        };

        const { count, rows } = await ctx.model.Comment.findAndCountAll(options);

        return {
            list: rows,
            pagination: {
                page: parseInt(page),
                pageSize: parseInt(pageSize),
                total: count,
                totalPages: Math.ceil(count / pageSize)
            }
        };
    }
}

module.exports = CommentService;